package teacher;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/GradeViewServlet")
public class GradeViewServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String type = request.getParameter("type");
        HttpSession session = request.getSession();
        Integer teacherId = (Integer) session.getAttribute("teacher_id");

        if (teacherId == null) {
            response.sendRedirect("teacher_student.jsp");
            return;
        }

        response.setContentType("application/json;charset=UTF-8");

        try {
            Connectmysql conn = new Connectmysql(
                    "jdbc:mysql://localhost:3306/exam",
                    "root",
                    "root",
                    "com.mysql.cj.jdbc.Driver"
            );

            if (conn.open()) {
                if ("class".equals(type)) {
                    // 查看班级某次考试成绩
                    int examId = Integer.parseInt(request.getParameter("exam_id"));
                    int classId = Integer.parseInt(request.getParameter("class_id"));

                    String sql = "SELECT s.student_id, s.student_no, s.name, sc.score, " +
                            "CASE WHEN sc.score >= 60 THEN '通过' ELSE '未通过' END AS is_passed " +
                            "FROM student_score sc " +
                            "JOIN student s ON sc.student_id = s.student_id " +
                            "JOIN exam e ON sc.exam_id = e.exam_id " +
                            "WHERE e.exam_id = ? AND s.class_id = ? AND e.teacher_id = ? " +
                            "AND sc.score IS NOT NULL";

                    ResultSet rs = conn.executeSql(sql, new Object[]{examId, classId, teacherId});
                    List<Map<String, Object>> grades = new ArrayList<>();

                    while (rs.next()) {
                        Map<String, Object> grade = new HashMap<>();
                        grade.put("student_id", rs.getInt("student_id"));
                        grade.put("student_no", rs.getString("student_no"));
                        grade.put("name", rs.getString("name"));
                        grade.put("score", rs.getDouble("score"));
                        grade.put("is_passed", rs.getString("is_passed"));
                        grades.add(grade);
                    }

                    response.getWriter().print(mapListToJson(grades));
                } else if ("student".equals(type)) {
                    // 查看单个学生所有课程成绩
                    String keyword = request.getParameter("keyword");

                    String sql = "SELECT c.course_name, sc.score, " +
                            "CASE WHEN sc.score >= 60 THEN '通过' ELSE '未通过' END AS is_passed, " +
                            "sc.submit_time " +
                            "FROM student_score sc " +
                            "JOIN exam e ON sc.exam_id = e.exam_id " +
                            "JOIN course c ON e.course_id = c.course_id " +
                            "JOIN student s ON sc.student_id = s.student_id " +
                            "WHERE (s.name LIKE ? OR s.student_no LIKE ?) AND e.teacher_id = ? " +
                            "AND sc.score IS NOT NULL";

                    ResultSet rs = conn.executeSql(sql, new Object[]{"%" + keyword + "%", "%" + keyword + "%", teacherId});
                    List<Map<String, Object>> grades = new ArrayList<>();

                    while (rs.next()) {
                        Map<String, Object> grade = new HashMap<>();
                        grade.put("course_name", rs.getString("course_name"));
                        grade.put("score", rs.getDouble("score"));
                        grade.put("is_passed", rs.getString("is_passed"));
                        grade.put("submit_time", rs.getTimestamp("submit_time").toString());
                        grades.add(grade);
                    }

                    response.getWriter().print(mapListToJson(grades));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().print("{\"error\": \"成绩查询失败: " + e.getMessage() + "\"}");
        }
    }

    private String mapListToJson(List<Map<String, Object>> list) {
        StringBuilder json = new StringBuilder("[");
        boolean firstItem = true;

        for (Map<String, Object> item : list) {
            if (!firstItem) {
                json.append(",");
            }
            firstItem = false;

            json.append("{");
            boolean firstEntry = true;

            for (Map.Entry<String, Object> entry : item.entrySet()) {
                if (!firstEntry) {
                    json.append(",");
                }
                firstEntry = false;

                json.append("\"")
                        .append(escapeJson(entry.getKey()))
                        .append("\":");

                Object value = entry.getValue();
                if (value instanceof String) {
                    json.append("\"")
                            .append(escapeJson((String) value))
                            .append("\"");
                } else {
                    json.append(value);
                }
            }

            json.append("}");
        }

        json.append("]");
        return json.toString();
    }

    private String escapeJson(String input) {
        if (input == null) return "";
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}